package com.file.parser.socialsecurity;


import com.file.bo.ResponseData;
import com.file.bo.socialsecurity.Shanxi2IndividualRecordSheet;
import com.file.bo.socialsecurity.Shanxi2InsuranceParticipation;
import com.file.constant.ErrorCode;
import com.file.parser.BasePdfParser;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.SpreadsheetDetectionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Shanxi2SocialSecurityPdfParser extends BasePdfParser {

    public ResponseData<String> parseShanxi2SocialSecurityPdfToJson(String daId, String filePath) {
        log.info("parseShanxi2SocialSecurityPdfToJson started, daId:{}", daId);
        String json = null;

        try {
            if (filePath.contains("cbzm")) {
                Shanxi2InsuranceParticipation shanxi2InsuranceParticipation = parseShanxi2InsuranceParticipation(filePath);
                json = JsonUtils.convertObjectToJson(shanxi2InsuranceParticipation);
            } else if (filePath.contains("qyd")) {//NOSONAR
                Shanxi2IndividualRecordSheet shanxi2IndividualRecordSheet = parseShanxi2IndividualRecordSheet(filePath);
                json = JsonUtils.convertObjectToJson(shanxi2IndividualRecordSheet);//NOSONAR
            } else {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseShanxi2SocialSecurityPdfToJson failed, new type not supported");
                return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseShanxi2SocialSecurityPdfToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseShanxi2SocialSecurityPdfToJson completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private Shanxi2InsuranceParticipation parseShanxi2InsuranceParticipation(String filePath) {
        Shanxi2InsuranceParticipation shanxi2InsuranceParticipation = parseShanxi2InsuranceParticipationHeader(filePath);
        List<List<String>> rowList = parseFileToRowList(filePath);
        parseListToBO(rowList, shanxi2InsuranceParticipation);
        return shanxi2InsuranceParticipation;
    }

    private Shanxi2InsuranceParticipation parseShanxi2InsuranceParticipationHeader(String filePath) {
        Shanxi2InsuranceParticipation shanxi2InsuranceParticipation = new Shanxi2InsuranceParticipation();
        String pdfText = parsePdfHeaderText(filePath)
                .replace(System.getProperty("line.separator", "\n"), StringUtils.EMPTY);
        String printTime = pdfText.substring(pdfText.lastIndexOf("打印时间：") + 5, pdfText.lastIndexOf("姓    名")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setPrintTime(printTime);
        String name = pdfText.substring(pdfText.lastIndexOf("姓    名") + 6, pdfText.lastIndexOf("身份证号")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setName(name);
        String idNo = pdfText.substring(pdfText.lastIndexOf("身份证号") + 4, pdfText.lastIndexOf("当前参保经办机构")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setIdNo(idNo);
        String agency = pdfText.substring(pdfText.lastIndexOf("当前参保经办机构") + 8, pdfText.lastIndexOf("当前参保单位名称")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setCurrentInsuranceAgency(agency);
        String unitName = pdfText.substring(pdfText.lastIndexOf("当前参保单位名称") + 8, pdfText.lastIndexOf("险种")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setCurrentInsuredUnitName(unitName);
        String insuranceStatus = pdfText.substring(pdfText.lastIndexOf("参保状态") + 4, pdfText.lastIndexOf("个人缴费明细")).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setInsuranceStatus(insuranceStatus);
        String remarks = pdfText.substring(pdfText.lastIndexOf("备注:") + 3).trim().replace(" ", "");
        shanxi2InsuranceParticipation.setRemarks(remarks);

        return shanxi2InsuranceParticipation;
    }

    private Shanxi2IndividualRecordSheet parseShanxi2IndividualRecordSheet(String filePath) { //NOSONAR
        Shanxi2IndividualRecordSheet shanxi2IndividualRecordSheet = new Shanxi2IndividualRecordSheet();
        return shanxi2IndividualRecordSheet;
    }

    private void parseListToBO(List<List<String>> rowList, Shanxi2InsuranceParticipation shanxi2InsuranceParticipation) {
        List<Shanxi2InsuranceParticipation.PaymentDetail> paymentDetailList = new ArrayList<>();
        shanxi2InsuranceParticipation.setPaymentDetailList(paymentDetailList);
        String sectionName = "";

        for (int i = 0; i < rowList.size(); i++) {
            List<String> cellList = rowList.get(i);
            if (StringUtils.equals(cellList.get(0), "险种")) {
                sectionName = "险种";
                continue;
            } else if (StringUtils.equalsAny(cellList.get(0), "参保状态", "个人缴费明细", "起止年月")) {
                sectionName = "个人缴费明细";
                continue;
            } else if (StringUtils.equals(cellList.get(0), "说明")) {
                return;
            }
            switch (sectionName) { //NOSONAR
                case "险种":
                    shanxi2InsuranceParticipation.setInsuranceType(cellList.get(0));
                    shanxi2InsuranceParticipation.setCoordinatedAreaPaymentStartAndEndTime(cellList.get(1).replaceAll(" ", ""));
                    shanxi2InsuranceParticipation.setCoordinatedAreaActualPaymentYears(cellList.get(2));
                    break;
                case "个人缴费明细":
                    if (StringUtils.isEmpty(cellList.get(0))) {
                        continue;
                    }
                    Shanxi2InsuranceParticipation.PaymentDetail paymentDetail = new Shanxi2InsuranceParticipation.PaymentDetail();
                    Shanxi2InsuranceParticipation.BasicPensionInsurance basicPensionInsurance = new Shanxi2InsuranceParticipation.BasicPensionInsurance();
                    paymentDetail.setBasicPensionInsurance(basicPensionInsurance);
                    paymentDetail.setStartAndEndDate(cellList.get(0).replaceAll(" ",""));
                    basicPensionInsurance.setPaymentBase(cellList.get(1));
                    basicPensionInsurance.setIndividualPayment(cellList.get(2));
                    paymentDetailList.add(paymentDetail);
                    break;
            }
        }
    }

    private List<List<String>> parseFileToRowList(String filePath) {
        // 1. 读取文件
        File pdf = new File(filePath);

        //页面所有table的记录，每一个元素代表下面一条记录cellList
        List<List<String>> rowList = new ArrayList<>();

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf)) {
            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            SpreadsheetDetectionAlgorithm detectionAlgorithm = new SpreadsheetDetectionAlgorithm();
            Map<Integer, List<Rectangle>> pageNumber2RectangleListMap = new HashMap<>();//key为页的序号， value为对应的Rectangle的list

            // 4. 获取每页的PageIterator
            PageIterator pageIterator = objectExtractor.extract();

            // 5. 解析每页的Rectangle
            // 如果单页pdf中有多个Rectangle，则解析出来的List<Rectangle>会有多个对象
            while (pageIterator.hasNext()) {
                Page page = pageIterator.next();
                List<Rectangle> rectangleList = detectionAlgorithm.detect(page);
                if (rectangleList.size() > 0) {
                    pageNumber2RectangleListMap.put(page.getPageNumber(), rectangleList);
                }
            }

            // 6.通过table位置获取表格具体内容
            SpreadsheetExtractionAlgorithm extractionAlgorithm = new SpreadsheetExtractionAlgorithm();

            // 如果单页pdf中有多个表格，则解析出来的List<Rectangle>会有多个对象
            for (Map.Entry<Integer, List<Rectangle>> entry : pageNumber2RectangleListMap.entrySet()) {
                Page page = objectExtractor.extract(entry.getKey());
                Rectangle rectangle = null;

                List<Rectangle> rectangleList = entry.getValue();
                for (Rectangle r : rectangleList) {
                    double rectangleHeight = r.getHeight();
                    if (Double.compare(rectangleHeight, 0) > 0) {
                        rectangle = r;
                        break;
                    }
                }
                if (rectangle == null) {
                    throw new RuntimeException("rectangle is null.");
                }

                if (entry.getKey() > 1) {
                    rectangle.setTop(rectangle.getTop());
                }
                rectangle.setBottom(rectangle.getBottom());
                Page area = page.getArea(rectangle);

                // 如果每页有多个表格，解析每一个table
                List<Table> tableList = extractionAlgorithm.extract(area);
                for (Table table : tableList) {
                    for (int i = 0; i < table.getRowCount(); i++) {
                        List<String> cellList = new ArrayList<>();//一条记录，每个单元格占一个元素
                        for (int j = 0; j < table.getColCount(); j++) {
                            cellList.add(table.getCell(i, j).getText(false));
                        }
                        rowList.add(cellList);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return rowList;
    }

    public static void main(String[] args) {
        Shanxi2SocialSecurityPdfParser shanxi2SocialSecurityPdfParser = new Shanxi2SocialSecurityPdfParser();
        String json;
         json = shanxi2SocialSecurityPdfParser.parseShanxi2SocialSecurityPdfToJson("", "D:\\data\\file\\socialsecurity\\山西\\zd47iaqw1769495560099409920_9c8b7716a10e5b090ba3dc9c5283fd93_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf").getData();
        System.out.println(json);

         json = shanxi2SocialSecurityPdfParser.parseShanxi2SocialSecurityPdfToJson("", "D:\\data\\file\\socialsecurity\\山西\\zd47iaqw1767811886850781184_97eeb2c43b05d1c9d752b74b60b78347_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf").getData();
        System.out.println(json);

         json = shanxi2SocialSecurityPdfParser.parseShanxi2SocialSecurityPdfToJson("", "D:\\data\\file\\socialsecurity\\山西\\zd47iaqw1767925313767919616_d1dd1a494b9c8ab671d0da15f1d71ec8_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf").getData();
        System.out.println(json);
    }

}
